<?php
namespace app\admin\model;

use think\Db;
use think\facade\Config;
use think\Model;

class ChannelResendReview extends Model
{
    /**
     * [reviewSms 审核渠道短信]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public static function reviewSms($request)
    {
        //检测表是否存在
        $tableName = 'bus_resend_order_' . $request['st'];

        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");

        if ($tableResult) {
            $where[] = ['check_status', 'eq', 0];
            $where[] = ['id', 'In', json_decode($request['reviewId'], true)];
            $where[] = ['cid', 'eq', $request['cid']];
            $batchId = uniqid();
            $data    = [
                'remarks'        => $request['desc'],
                'check_status'      => $request['status'],
                'batch_number'    => $batchId,
                'check_time' => date('Y-m-d H:i:s'),
                'assessor'    => session('username'),
            ];
            trace('表' . $tableName . '--审核短信--id:' . $request['reviewId']);
            Db::startTrans();
            try {
                $updateResult = Db::table($tableName)->where($where)->update($data);
                if ($updateResult != false) {
                    // 提交事务
                    Db::commit();
                    // $url         = 'http://183.240.150.13:3389/SMS/review/';
                    $url         = Config::get('CHANNEL_RESEND_REVIEW');
                    $requestData = [
                        'tableDate' => $request['st'],
                        'cid'       => $request['cid'],
                        'batchId'   => $batchId,
                    ];
                    trace('渠道审核请求java--' . json_encode($requestData));
                    $javaResult = curl_post($url, $requestData);
                    trace('渠道审核请求返回---' . json_encode($javaResult));
                    
                    $result = ['code' => 200, 'msg' => '处理成功'];
                } else {
                    Db::rollback();
                    $result = ['code' => 422, 'msg' => '不存在需要审核的数据'];
                }
                //请求java
            } catch (\Exception $e) {
                trace('渠道审核报错---' . $e);
                // 回滚事务
                Db::rollback();
                $result = ['code' => 422, 'msg' => '处理失败'];
            }

        } else {
            $result = ['code' => 422, 'msg' => '不存在该数据表'];
        }

        return $result;

    }

    /**
     * [batchReviewSms 批量审核短信]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public static function batchReviewSms($request)
    {
        
        //审核表
        $tableName = 'bus_resend_order_' . $request['st'];

        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");

        if ($request['cid'] != '' && is_numeric($request['number']) && $tableResult) {

            $where[] = ['o.check_status', 'eq', 0];
            if ($request['cid'] != '') {
                $where[] = ['o.cid', 'eq', $request['cid']];
            }


            // if ($request['create_time'] != '') {
            //     $where[] = ['o.create_time', '> time', $request['create_time']];
            // }

            // if ($request['end_time'] != '') {
            //     $where[] = ['o.create_time', '< time', $request['end_time']];
            // }

            if ($request['bus_push_sms'] != '') {
                $where[] = ['sms.bus_push_sms', 'like', '%' . $request['bus_push_sms'] . '%'];
            }
            if ($request['phone'] != '') {
                $where[] = ['o.phone', 'eq', $request['phone']];
            }

            if ($request['msg'] != '') {
                $where[] = ['o.msg', 'like', '%' . $request['msg'] . '%'];
            }

            if ($request['plat_id'] != '') {
                $where[] = ['o.plat_id', 'eq', $request['plat_id']];
            }



            $orderIdArr = Db::table($tableName)->alias('o')
                ->field('o.id')
                ->join('bus_platfrom bp', 'bp.plat_id = o.plat_id')
                ->join('bus_order_sms_content_' . $request['st'] . ' sms', 'o.table_order_id = sms.bus_order_id', 'LEFT')
                ->where($where)
                ->limit($request['number'])
                ->column('o.id');

            trace('渠道批量更新表' . $tableName . '----id:' . json_encode($orderIdArr));
            if ($orderIdArr) {
                $batchId = uniqid();
                $data    = [
                    'remarks'        => $request['desc'],
                    'check_status'      => $request['status'],
                    'batch_number'    => $batchId,
                    'check_time' => date('Y-m-d H:i:s'),
                    'assessor'    => session('username'),
                ];
                Db::startTrans();
                try {
                    $updateResult = Db::table($tableName)->where('id', 'IN', $orderIdArr)->where('check_status', 'eq', 0)->where('cid', 'eq', $request['cid'])->update($data);
                    if ($updateResult != false) {
                        // $url         = 'http://183.240.150.13:3389/SMS/review/';
                        // 提交事务
                        Db::commit();
                        $url         = Config::get('CHANNEL_RESEND_REVIEW');
                        $requestData = [
                            'tableDate' => $request['st'],
                            'cid'       => $request['cid'],
                            'batchId'   => $batchId,
                        ];
                        trace('渠道批量审核请求java--' . json_encode($requestData));
                        $javaResult = curl_post($url, $requestData);
                        trace('渠道批量请求返回---' . json_encode($javaResult));
                        
                        $result = ['code' => 200, 'msg' => '处理成功'];
                    } else {
                        Db::rollback();
                        $result = ['code' => 422, 'msg' => '不存在需要审核的数据'];
                    }
                    //请求java
                } catch (\Exception $e) {
                    trace('渠道批量短信审核报错---' . $e);
                    // 回滚事务
                    Db::rollback();
                    $result = ['code' => 422, 'msg' => '处理失败'];
                }

            }
        } else {
            $result = ['code' => 422, 'msg' => '无需要审核的数据'];
        }

        return $result;

    }

    /**
     * [reviewChannels 短信审核列表]
     * @return [type] [description]
     */
    public static function reviewChannels($request)
    {
        //检测表是否存在
        $tableName = 'bus_resend_order_' . $request['st'];

        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");
        if ($tableResult) {
            $where[] = ['o.status', 'eq', 0];
            if ($request['cid'] != '') {
                $where[] = ['o.cid', 'eq', $request['cid']];
            }
            $data = Db::table($tableName)->alias('o')
                ->field('o.status,o.cid,sum(o.phone_size) as phone_size,c.company_name,count(o.cid) as order_all')
                ->join('bus_channel c', 'o.cid = c.channel_id')
                ->where($where)
                ->group('o.cid')
                ->paginate($request['limit'], false, $request)
                ->toarray();

            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['company_name'] = $data['data'][$k]['company_name'] . '(' . $data['data'][$k]['cid'] . ')';
                switch ($v['status']) {
                    case '0':
                        $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-orange status-jy">待审核</span>';
                        break;
                    case '1':
                        $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-green status-qy">通过</span>';
                        break;
                    case '2':
                        $data['data'][$k]['status'] = '<span class="layui-badge status-qy">失败</span>';
                        break;
                    default:
                        $data['data'][$k]['status'] = '未定义';
                        break;
                }
            }
        } else {
            $data['total'] = 0;
            $data['data']  = [];
        }
        return $data;
    }

    /**
     * [reviewOne 单条短信审核]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public static function reviewOne($request)
    {
        //检测表是否存在
        $tableName = 'bus_resend_order_' . $request['table_time'];

        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");
        if ($tableResult) {
            $where[] = ['check_status', 'eq', 0];
            $where[] = ['id', 'eq', $request['reviewId']];
            $smsInfo = Db::table($tableName)->where($where)->find();
            // halt($smsInfo);
            if ($smsInfo) {
                $batchNumber = uniqid();
                $data    = [
                    'remarks'        => $request['desc'],
                    'check_status'      => $request['status'],
                    'batch_number'    => $batchNumber,
                    'check_time' => date('Y-m-d H:i:s'),
                    'assessor'    => session('username'),
                ];
                Db::startTrans();
                try {
                    $updateResult = Db::table($tableName)->where($where)->update($data);
                    if ($updateResult != false) {
                        // $url         = 'http://183.240.150.13:3389/SMS/review/';
                        // 提交事务
                        Db::commit();
                        $url         = Config::get('CHANNEL_RESEND_REVIEW');
                        $requestData = [
                            'tableDate' => $request['table_time'],
                            'cid'       => $smsInfo['cid'],
                            'batchId'   => $batchNumber,
                        ];
                        trace('单个渠道重发审核请求java--' . json_encode($requestData));
                        $javaResult = curl_post($url, $requestData);
                        trace('单个渠道重发审核请求返回---' . json_encode($javaResult));
                        
                        $result = ['code' => 200, 'msg' => '处理成功'];
                    } else {
                        Db::rollback();
                        $result = ['code' => 422, 'msg' => '不存在需要审核的数据'];
                    }
                    //请求java
                } catch (\Exception $e) {
                    trace('单个渠道重发审核报错---' . $e);
                    // 回滚事务
                    Db::rollback();
                    $result = ['code' => 422, 'msg' => '处理失败'];
                }
            } else {
                trace('单个渠道重发审核请求数据---' . json_encode($request));
                $result = ['code' => 422, 'msg' => '无该订单信息'];
            }
        } else {
            trace('单个渠道重发审核无表信息---' . json_encode($request));
            $result = ['code' => 422, 'msg' => '无表：' . $tableName . '信息'];
        }
        return $result;
    }

    /**
     * [getAllSms 获取所有短信]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public static function getAllSms($request)
    {
        $tableName = 'bus_resend_order_' . $request['table_time'];

        //检测表是否存在
        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");

        if ($tableResult) {
            $where = [];
            // $where[] = ['o.check_status', 'eq', 0];
            if ($request['cid'] != '') {
                $where[] = ['o.cid', 'eq', $request['cid']];
            }

            if ($request['state'] != '') {
                $where[] = ['o.check_status', 'eq', $request['state']];
            }

            // if ($request['create_time'] != '') {
            //     $where[] = ['o.create_time', '> time', $request['create_time']];
            // }

            // if ($request['end_time'] != '') {
            //     $where[] = ['o.create_time', '< time', $request['end_time']];
            // }

            if ($request['send_text'] != '') {
                $where[] = ['sms.bus_push_sms', 'like', '%' . $request['send_text'] . '%'];
            }
            if ($request['phone'] != '') {
                $where[] = ['o.phone', 'eq', $request['phone']];
            }

            if ($request['msg'] != '') {
                $where[] = ['o.msg', 'like', '%' . $request['msg'] . '%'];
            }

            if ($request['plat_id'] != '') {
                $where[] = ['o.plat_id', 'eq', $request['plat_id']];
            }

            $data = Db::table($tableName)->alias('o')
                ->field('o.*,c.company_name,sms.bus_push_sms,bp.platfrom')
                ->join('bus_channel c', 'o.cid = c.channel_id')
                ->join('bus_platfrom bp', 'bp.plat_id = o.plat_id')
                ->join('bus_order_sms_content_' . $request['table_time'] . ' sms', 'o.table_order_id = sms.bus_order_id', 'LEFT')
                ->where($where)
                ->paginate($request['limit'], false, $request)
                ->toArray();

                foreach ($data['data'] as $k => $v) {
                    switch ($v['check_status']) {
                        case 0:
                            $data['data'][$k]['check_status'] = '<span class="layui-badge layui-bg-orange">待审核</span>';
                            break;
                        case 1:
                            $data['data'][$k]['check_status'] = '<span class="layui-badge layui-bg-green">审核成功</span>';
                            break;
                        case 2:
                            $data['data'][$k]['check_status'] = '<span class="layui-badge layui-bg-red">审核失败</span>';
                            break;
                        default:
                            $data['data'][$k]['check_status'] = '';
                            break;
                    }
                    switch ($v['status']) {
                        case '0':
                            $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-orange">未处理</span>';
                            break;
                        case '1':
                            $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-green">处理成功</span>';
                            break;
                        case '2':
                            $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-red">处理异常</span>';
                            break;
                        default:
                            $data['data'][$k]['status'] = '未定义';
                            break;
                    }
                    switch ($v['isp_host']) {
                        case '10086':
                            $data['data'][$k]['isp_host'] = '移动';
                            break;
                        case '10000':
                            $data['data'][$k]['isp_host'] = '电信';
                            break;
                        case '10010':
                            $data['data'][$k]['isp_host'] = '联通';
                            break;
                        default:
                            $data['data'][$k]['isp_host'] = '未定义';
                            break;
                    }
                    $data['data'][$k]['company_name'] = $data['data'][$k]['company_name'] . '(' . $data['data'][$k]['cid'] . ')';
                    $data['data'][$k]['platfrom'] = $data['data'][$k]['platfrom'] . '(' . $data['data'][$k]['plat_id'] . ')';
                }
        } else {
            $data['total'] = 0;
            $data['data']  = [];
        }

        return $data;

    }


    /**
     * [getListAll 获取所有未审核的]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public static function getListAll($request)
    {
        $tableName = 'bus_resend_order_' . $request['table_time'];

        //检测表是否存在
        $tableResult = Db::query('SHOW TABLES LIKE ' . "'" . $tableName . "'");
        // halt($tableName);
        if ($tableResult) {
            
            $where[] = ['o.check_status', 'eq', 0];
            if ($request['cid'] != '') {
                $where[] = ['o.cid', 'eq', $request['cid']];
            }


            // if ($request['create_time'] != '') {
            //     $where[] = ['o.create_time', '> time', $request['create_time']];
            // }

            // if ($request['end_time'] != '') {
            //     $where[] = ['o.create_time', '< time', $request['end_time']];
            // }

            if ($request['bus_push_sms'] != '') {
                $where[] = ['sms.bus_push_sms', 'like', '%' . $request['bus_push_sms'] . '%'];
            }
            if ($request['phone'] != '') {
                $where[] = ['o.phone', 'eq', $request['phone']];
            }

            if ($request['msg'] != '') {
                $where[] = ['o.msg', 'like', '%' . $request['msg'] . '%'];
            }

            if ($request['plat_id'] != '') {
                $where[] = ['o.plat_id', 'eq', $request['plat_id']];
            }
            // $a = Db::table($tableName)->alias('o')
            //     ->field('o.*,c.company_name')
            //     ->join('bus_channel c', 'o.cid = c.channel_id')
            //     ->where($where)
            //     ->select();
            //     // ->toOboject();
            //     // halt(Db::table($tableName)->getLastSql());
            // halt($a);
            // dump($where);
            $data = Db::table($tableName)->alias('o')
                ->field('o.*,c.company_name,sms.bus_push_sms,bp.platfrom')
                ->join('bus_channel c', 'o.cid = c.channel_id')
                ->join('bus_platfrom bp', 'bp.plat_id = o.plat_id')
                ->join('bus_order_sms_content_' . $request['table_time'] . ' sms', 'o.table_order_id = sms.bus_order_id', 'LEFT')
                ->where($where)
                // ->group('o.id')
                ->paginate($request['limit'], false, $request)
                ->toArray();
            // halt($data);
            // halt(Db::table($tableName)->getLastSql());
                // ->each(function($item, $key){
                //     $item->company_name =  $item->company_name . '(' . $item->cid . ')';
                //     switch ($item->check_status) {
                //         case 0:
                //             $item->check_status = '<span class="layui-badge layui-bg-orange">待审核</span>';
                //             break;
                //         case 1:
                //             $item->check_status = '<span class="layui-badge layui-bg-green">审核成功</span>';
                //             break;
                //         case 2:
                //             $item->check_status = '<span class="layui-badge layui-bg-red">审核失败</span>';
                //             break;
                //         default:
                //             $item->check_status = '';
                //             break;
                //     }
                //     switch ($item->status) {
                //         case 0:
                //             $item->status = '<span class="layui-badge layui-bg-orange">未处理</span>';
                //             break;
                //         case 1:
                //             $item->status = '<span class="layui-badge layui-bg-green">处理成功</span>';
                //             break;
                //         case 2:
                //             $item->status = '<span class="layui-badge layui-bg-red">处理异常</span>';
                //             break;
                //         default:
                //             $item->status = '';
                //             break;
                //     }
                // });
                foreach ($data['data'] as $k => $v) {
                    switch ($v['check_status']) {
                        case 0:
                            $data['data'][$k]['check_status'] = '<span class="layui-badge layui-bg-orange">待审核</span>';
                            break;
                        case 1:
                            $data['data'][$k]['check_status'] = '<span class="layui-badge layui-bg-green">审核成功</span>';
                            break;
                        case 2:
                            $data['data'][$k]['check_status'] = '<span class="layui-badge layui-bg-red">审核失败</span>';
                            break;
                        default:
                            $data['data'][$k]['check_status'] = '';
                            break;
                    }
                    switch ($v['status']) {
                        case '0':
                            $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-orange">未处理</span>';
                            break;
                        case '1':
                            $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-green">处理成功</span>';
                            break;
                        case '2':
                            $data['data'][$k]['status'] = '<span class="layui-badge layui-bg-red">处理异常</span>';
                            break;
                        default:
                            $data['data'][$k]['status'] = '未定义';
                            break;
                    }
                    switch ($v['isp_host']) {
                        case '10086':
                            $data['data'][$k]['isp_host'] = '移动';
                            break;
                        case '10000':
                            $data['data'][$k]['isp_host'] = '电信';
                            break;
                        case '10010':
                            $data['data'][$k]['isp_host'] = '联通';
                            break;
                        default:
                            $data['data'][$k]['isp_host'] = '未定义';
                            break;
                    }
                    $data['data'][$k]['company_name'] = $data['data'][$k]['company_name'] . '(' . $data['data'][$k]['cid'] . ')';
                    $data['data'][$k]['platfrom'] = $data['data'][$k]['platfrom'] . '(' . $data['data'][$k]['plat_id'] . ')';
                }
                // ->toArray();
            // halt($data);
            // halt(Db::table($tableName)->getLastSql());
        } else {
            // halt('222');
            $data['total'] = 0;
            $data['data']  = [];
        }

        return $data;

    }

}
